package lumis.portal.serviceinterfaceinstance.serialization;

import java.util.List;

import lumis.portal.PortalException;
import lumis.portal.serialization.DeserializationContext;
import lumis.portal.serialization.operation.ConfigDependencyAnalyzer;
import lumis.portal.serialization.operation.ConfigForeignKey;
import lumis.portal.serialization.operation.ConfigPersistence;
import lumis.portal.serialization.operation.IConfigPersister;
import lumis.portal.serviceinterfaceinstance.ServiceInterfaceInstanceConfig;

/**
 * Responsible for analyze foreign key dependencies of a service interface instance being deserialized.
 *
 * @version $Revision: 5769 $ $Date: 2007-02-01 12:00:07 -0200 (Thu, 01 Feb 2007) $
 * @since 4.0.9
 */
public class ServiceInterfaceInstanceConfigDependencyAnalyzer extends ConfigDependencyAnalyzer<ServiceInterfaceInstanceConfig>
{
	private final ServiceInterfaceInstancePersistableConfig serviceInterfaceInstancePersistableConfig;

	public ServiceInterfaceInstanceConfigDependencyAnalyzer(DeserializationContext deserializationContext, List<ConfigForeignKey> configForeignKeys, ServiceInterfaceInstancePersistableConfig serviceInterfaceInstancePersistableConfig)
	{
		super(deserializationContext, configForeignKeys, serviceInterfaceInstancePersistableConfig.getServiceInterfaceInstanceConfig());
		this.serviceInterfaceInstancePersistableConfig = serviceInterfaceInstancePersistableConfig;
	}

	@Override
	protected ConfigPersistence getConfigPersistence(IConfigPersister configPersister)
	{
		return new ConfigPersistence(serviceInterfaceInstancePersistableConfig, configPersister);
	}

	@Override
	public void persist(IConfigPersister configPersister, boolean firstPersistenceIsRequired) throws PortalException
	{
		analyze(configPersister);
		if (canPersist)
		{
			ServiceInterfaceInstancePersistableConfig newServiceInterfaceInstancePersistableConfig = new ServiceInterfaceInstancePersistableConfig(persistableConfig, serviceInterfaceInstancePersistableConfig.getCustomProperties());
			if (!configPersister.persistConfig(deserializationContext, newServiceInterfaceInstancePersistableConfig, true) && firstPersistenceIsRequired)
				throw new IllegalStateException("Error persisting deserialized config of type '" + newServiceInterfaceInstancePersistableConfig.getClass().getName() + "'.");
		}
	}

	public ServiceInterfaceInstancePersistableConfig getMappedServiceInterfaceInstancePersistableConfig()
	{
		ServiceInterfaceInstanceConfig mappedServiceInterfaceInstanceConfig = super.getMappedPersistableConfig();
		return new ServiceInterfaceInstancePersistableConfig(mappedServiceInterfaceInstanceConfig, serviceInterfaceInstancePersistableConfig.getCustomProperties());
	}
}
